﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Globalization;

public partial class FrontPage : System.Web.UI.Page
{
    ServerObject mServerObject = null;

    public string detailsDataGrid = string.Empty;

    protected override void InitializeCulture()
    {
        System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(HttpContext.Current.Request.UserLanguages[0]);
        System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(HttpContext.Current.Request.UserLanguages[0]);

        base.InitializeCulture();
    }

    private bool CheckServerObject()
    {
        bool result = false;

        if (Session["ServerModule"] != null)
        {
            mServerObject = (ServerObject)Session["ServerModule"];
        }
        else
        {
            mServerObject = new ServerObject();
            Session["ServerModule"] = mServerObject;
        }

        if (mServerObject != null)
        {
            result = true;
        }

        return result;
    }

    private void ShowPanel(string panelName)
    {
        #region Hide panels

        stapeZeroPanel.Visible = false;
        RegFormMenuPanel.Visible = false;
        RegFormFamiliaPanel.Visible = false;
        RegFormStep1Panel.Visible = false;
        RegFormStep2Panel.Visible = false;
        RegFormStep3PanelFamilySelection.Visible = false;
        RegFormStep3Panel.Visible = false;
        RegFormStep6Panel.Visible = false;
        statisticaInregistrarilorPanel.Visible = false;
        emailDiv.Visible = false;
        fieldPassword.Visible = false;
        fieldPasswordConfirm.Visible = false;
        ProgramareTruePanel.Visible = false;
        RegFormSelectPersonTypePanel.Visible = false;
        ClearRegForm();

        personalInfoTablePanel.Visible = false;

        #endregion Hide panels

        try
        {
            #region Get Panel Name

            switch (panelName)
            {
                #region Users
                case "stapeZeroPanel":
                    stapeZeroPanel.Visible = true;

                    if (CheckServerObject())
                    {
                        mServerObject.InfoText(this, "Info Step Zero");
                    }

                    break;

                #endregion Users

                #region RegForm

                #region RegFormSelectPerson
                case "RegFormSelectPersonTypePanel":
                    RegFormSelectPersonTypePanel.Visible = true;
                    break;
                #endregion RegFormSelectPerson

                #region RegForm1
                case "RegFormStep1Panel":
                    RegFormStep1Panel.Visible = true;
                    emailDiv.Visible = true;
                    fieldPassword.Visible = true;
                    fieldPasswordConfirm.Visible = true;
                    
                    if (!IsPostBack)
                    {
                        DataTable countryList = mServerObject.GetCountryList();
                        mServerObject.fillFrontPageSelector(countryNastereDDL, countryList, "DenumireJudet", "IdJudet");
                        mServerObject.fillFrontPageSelector(countryDomDDL, countryList, "DenumireJudet", "IdJudet");

                        int sextype = (int)Utils.Constants.SexList;
                        int languageCode = mServerObject.UserLanguageID;

                        DataTable sexList = mServerObject.GetSexTypes(sextype, languageCode);
                        mServerObject.fillFrontPageSelector(sexDDL, sexList, "Name", "Code");  
                    }
                   
                    break;
                #endregion RegForm1

                #region RegForm2
                case "RegFormStep2Panel":
                    RegFormStep2Panel.Visible = true;
                    break;
                #endregion RegForm2

                #region FamilySelection   for PROGRAMARE

                case "RegFormStep3PanelFamilySelection":
                    if (mServerObject.isLogetUser)
                    {
                        RegFormMenuPanel.Visible = true;
                        RegFormStep3PanelFamilySelection.Visible = true;
                        {
                            int solicitantID = mServerObject.UserID;

                            DataTable famiyMebers = mServerObject.GetFamilyListByUserID(solicitantID, true);
                            famiyMebers.Columns.Add("StatusCheked", typeof(bool));

                            if (famiyMebers.Rows.Count == 0)
                            { newFamilyMemberHiddenField.Value = "New"; }
                            else
                            { newFamilyMemberHiddenField.Value = "Old"; }


                            for (int i = 0; i < famiyMebers.Rows.Count; i++)
                            {
                                famiyMebers.Rows[i]["StatusCheked"] = false;
                            }

                            if (famiyMebers != null && famiyMebers.Rows.Count > 0)
                            {
                                programareFamilyMembersGridView.DataSource = famiyMebers;
                                programareFamilyMembersGridView.DataBind();
                            }

                            int parentID = 0;
                            DataTable serviciuTable = mServerObject.GetServicesList(parentID);
                            mServerObject.fillSelector(ServiciuRegForm3Selector, serviciuTable, "Denumirea", "ID Service");
                        }
                    }

                    break;

                #endregion FamilySelection

                #region RegForm3
                case "RegFormStep3Panel":
                    RegFormMenuPanel.Visible = true;
                    RegFormStep3Panel.Visible = true;
                    
                    int preferedIdConsulat = 0;
                    if (Session["UserData"] != null)
                    {
                        DataTable userData = (DataTable)Session["UserData"];
                        if (userData != null && userData.Rows.Count == 1)
                        {
                            preferedIdConsulat = (int)userData.Rows[0]["PreferedIdConsulat"];
                            consulatForDeservireLabel.Text = "Misiunea dumneavoastră este : " + userData.Rows[0]["PreferedDenumireConsulat"].ToString();                                                          
                        }

                        int parentID = 0;
                        DataTable serviciuTable = mServerObject.GetServicesList(parentID);
                        mServerObject.fillSelector(ServiciuRegForm3Selector, serviciuTable, "Denumirea", "ID Service");
                    }
                    break;
                #endregion RegForm3

                #region Family Pesonal Data
                case "RegFormFamiliaPanel":
                    if (mServerObject.isLogetUser)
                    {
                        RegFormMenuPanel.Visible = true;
                        RegFormFamiliaPanel.Visible = true;

                        DataTable rudenieList = mServerObject.GetClassifierByTypeID((int)Utils.Constants.GradDeRudenie);
                        mServerObject.fillFrontPageSelector(gradRudenieDropDownList, rudenieList, "Name", "Code");

                        int parentUserID = mServerObject.UserID;

                        DataTable familyList = mServerObject.GetFamilyListByUserID(parentUserID, false);
                        if (familyList.Rows.Count == 0)
                        { newFamilyMemberHiddenField.Value = "New"; }
                        else
                        { newFamilyMemberHiddenField.Value = "Old"; }

                        familyList.Rows.Add();
                        familyList.Rows[familyList.Rows.Count - 1]["Name"] = "-> Adaugă membru nou <-";
                        familyList.Rows[familyList.Rows.Count - 1]["Code"] = 0;


                        mServerObject.fillFrontPageSelector(membruFamilieDropDownList, familyList,  "Name", "Code");

                        DataTable countryList = mServerObject.GetCountryList();
                        mServerObject.fillFrontPageSelector(familiaCountryNastereDDL, countryList, "DenumireJudet", "IdJudet");
                        mServerObject.fillFrontPageSelector(familiaCountryDomDDL, countryList, "DenumireJudet", "IdJudet");

                        int sextype = (int)Utils.Constants.SexList;
                        int languageCode = mServerObject.UserLanguageID;

                        DataTable sexList = mServerObject.GetSexTypes(sextype, languageCode);
                        mServerObject.fillFrontPageSelector(familiaSexDDL, sexList, "Name", "Code");

                        FillFamilyMemdersForm();
                    }
                    break;
                #endregion Family Pesonal Data

                #region RegForm6
                case "RegFormStep6Panel":
                    RegFormMenuPanel.Visible = true;
                    RegFormStep6Panel.Visible = true;
                    break;
                #endregion RegForm6

                #region StatisticaInregistrarilor
                case "statisticaInregistrarilorPanel":
                    RegFormMenuPanel.Visible = true;
                    statisticaInregistrarilorPanel.Visible = true;

                    int idSolicitant = 0;
                    DataTable userTable = (DataTable)Session["UserData"];
                    if (userTable != null && userTable.Rows.Count > 0)
                    {
                        string stringUser = userTable.Rows[0]["ID"].ToString();
                        int.TryParse(stringUser, out idSolicitant);
                    }

                    DataTable statTable = mServerObject.GetStatisticaInregistrarilor(idSolicitant);
                    if (statTable != null && statTable.Rows.Count > 0)
                    {
                        statisticaInregistrarilorGridView.DataSource = statTable;
                        statisticaInregistrarilorGridView.DataBind();
                    }
                    else
                    {
                        statisticaInregistrarilorGridView.DataSource = null;
                        statisticaInregistrarilorGridView.DataBind();
                    }
                    break;
                #endregion

                #region ProgramareTrue
                case "ProgramareTruePanel":
                    RegFormMenuPanel.Visible = true;
                    ProgramareTruePanel.Visible = true;
                    break;
                #endregion

                #region Pesonal Data Panel
                case "personalInfoTablePanel":
                    if (mServerObject.isLogetUser)
                    {
                        RegFormMenuPanel.Visible = true;
                        personalInfoTablePanel.Visible = true;

                        DataTable countryList = mServerObject.GetCountryList();
                        mServerObject.fillFrontPageSelector(personalCountryNastereDDL, countryList, "DenumireJudet", "IdJudet");
                        mServerObject.fillFrontPageSelector(personalCountryDomDDL, countryList, "DenumireJudet", "IdJudet");

                        int sextype = (int)Utils.Constants.SexList;
                        int languageCode = mServerObject.UserLanguageID;

                        DataTable sexList = mServerObject.GetSexTypes(sextype, languageCode);
                        mServerObject.fillFrontPageSelector(personalSexDDL, sexList, "Name", "Code");

                        FillPersonalDataPanel();
                    }
                    break;
                #endregion Personal Data Panel

                #endregion RegForm

                default:
                    break;
            }

            #endregion Get Panel Name
            
        }
        catch (Exception exception)
        {
            mServerObject.LogFatal(exception.Message);
        }
    }       

    protected void Page_Load(object sender, EventArgs e)
    {
        #region LogOutAction
        if (Request["action"] != null)
        {
            string action = Request["action"].ToString();

            switch (action)
            {
                case "logout":
                    Session["UserData"] = null;
                    Session["ServerModule"] = null;
                    Response.Redirect("Default.aspx", true);
                    break;
                default:
                    break;
            }
        }
        #endregion LogOutAction

        DataTable userData = (DataTable)Session["UserData"];              
        
        if (CheckServerObject())
        {
            if (!IsPostBack)
            {
                string areaGUID = string.Empty;
                isPersonJuridiHiddenFieldID.Value = "0";
                if (Request["area"] != null)
                {
                    areaGUID = Request["area"].ToString();

                    string areaName = areaGUID; //mServerObject.GetAreaName(areaGUID);
                    // area for each of administration entry points
                    switch (areaName)
                    {
                        case "orgForm":
                            ShowPanel(RegFormStep3PanelFamilySelection.ID);
                            break;

                        case "regForm":
                            ShowPanel(RegFormStep1Panel.ID);
                            break;

                        case "info":
                            Response.Redirect("home.aspx", true);
                            break;
                        case "about":
                            Response.Redirect("About.aspx", true);
                            break;

                        default:
                            Response.Redirect("home.aspx", true);
                            break;
                    }
                }
                else
                {
                    if (Request["programare"] != null)
                    {
                        string stringProgramare = Server.UrlDecode(Request.QueryString["programare"]);

                        string decodeString = mServerObject.DecodeCriptedString(stringProgramare);
                        if (!decodeString.Equals(string.Empty))
                        {
                            string familyString = string.Empty;
                            string[] totalList = decodeString.Split('*');

                            DataTable totalsMemberstoRegisre = new DataTable();
                            totalsMemberstoRegisre.Columns.Add("FamId", typeof(string));
                            totalsMemberstoRegisre.Columns.Add("ParID", typeof(string));
                            totalsMemberstoRegisre.Columns.Add("Name", typeof(string));

                            if (totalList != null && totalList.Length == 2)
                            {
                                string[] anyPerson = totalList[1].Split('@');
                                if (anyPerson != null && anyPerson.Length > 0)
                                {
                                    for (int i = 0; i < anyPerson.Length; i++)
                                    {
                                        string[] oneperson = anyPerson[i].Split('_');
                                        if (oneperson != null && oneperson.Length == 3)
                                        {
                                            totalsMemberstoRegisre.Rows.Add(oneperson[0], oneperson[1], oneperson[2]);
                                        }
                                    }
                                }
                            }

                            if (totalsMemberstoRegisre.Rows.Count > 0)
                            {
                                List<string> listProgramare = new List<string>(totalList[0].Split('_'));
                                if (listProgramare != null && listProgramare.Count == 5)
                                {
                                    string stringConsulat = listProgramare[0];
                                    string stringServiciu = listProgramare[1];
                                    string stringCalendar = listProgramare[2];
                                    string stringHours = listProgramare[3];
                                    string stringIdCalendar = listProgramare[4];

                                    int idConsulat = 0;
                                    int.TryParse(stringConsulat, out idConsulat);

                                    DateTime dataSolicitarii = DateTime.Now.Date;
                                    DateTime dataProgramarii = DateTime.Now.Date;
                                    DateTime.TryParse(stringCalendar, out dataProgramarii);

                                    TimeSpan emptyOraProgramarii = TimeSpan.MinValue;
                                    TimeSpan oraProgramarii = TimeSpan.MinValue;

                                    int selectedIDCalendar = 0;
                                    int.TryParse(stringIdCalendar, out selectedIDCalendar);

                                    TimeSpan.TryParse(stringHours, out oraProgramarii);                                  

                                    if (dataProgramarii != dataSolicitarii && oraProgramarii != emptyOraProgramarii)
                                    {
                                        int idService = 0;
                                        int.TryParse(stringServiciu, out idService);

                                        for (int i = 0; i < totalsMemberstoRegisre.Rows.Count; i++)
                                        {
                                            int idMFam = 0;
                                            int.TryParse(totalsMemberstoRegisre.Rows[i]["FamId"].ToString(), out idMFam);

                                            int intParentID = 0;
                                            int.TryParse(totalsMemberstoRegisre.Rows[i]["ParID"].ToString(), out intParentID);

                                            DataTable moreregistersFam = mServerObject.ChekIfExistAnyRegistrations(idConsulat, idMFam);

                                            if (moreregistersFam != null && moreregistersFam.Rows.Count == 0)
                                            {
                                                bool resultFam = mServerObject.AddNewProgramare(idMFam, intParentID, idConsulat, dataSolicitarii, dataProgramarii, oraProgramarii, idService, selectedIDCalendar);

                                                if (resultFam)
                                                {
                                                    DataTable resultTableFam = mServerObject.GetProgramareID(idMFam, intParentID, idConsulat, dataSolicitarii, dataProgramarii, oraProgramarii, idService);
                                                    if (resultTableFam != null && resultTableFam.Rows.Count > 0)
                                                    {
                                                        string progIDStringFam = resultTableFam.Rows[0]["PROG_ID"].ToString();
                                                        programareIDlabel.Text += " <br /> Numarul de programare pentru " + totalsMemberstoRegisre.Rows[i]["Name"].ToString() + " : " + progIDStringFam;
                                                        ShowPanel(ProgramareTruePanel.ID);
                                                    }
                                                }
                                                else
                                                {
                                                    programareIDlabel.Text += "<br /> Nu a reușit programarea pentru " + totalsMemberstoRegisre.Rows[i]["Name"].ToString() + " încercați mai târziu ";
                                                    ShowPanel(ProgramareTruePanel.ID);
                                                }
                                            }
                                            else
                                            {
                                                programareIDlabel.Text += "<br />" + totalsMemberstoRegisre.Rows[i]["Name"].ToString() + " este deja programat! ";
                                                ShowPanel(ProgramareTruePanel.ID);
                                            }
                                        }                                                         
                                    }
                                }
                            }
                            else
                            {
                                programareIDlabel.Text = "Nu a fost selectata nici o persoana din familia dumneavoastra care sa fie programata!";
                                programareIDlabel.Text += "<br />Va rugam selectati cel putin o persoana!";
                                ShowPanel(ProgramareTruePanel.ID);
                            }
                        }
                    }
                    else
                    {
                        Response.Redirect("home.aspx", true);
                    }
                }
            }            
        }
        else
        {
            //ShowPanel(stapeZeroPanel.ID);
            Response.Redirect("home.aspx", true);
        }
    }

    #region RegForm1Panel

    public void ServerValidation(object source, ServerValidateEventArgs args)
    {
        try
        {
            string imputEmail = args.Value.ToString();
            DataTable dt = mServerObject.ChekExistRegistredEmail(imputEmail);

            if (dt != null && dt.Rows.Count > 0)
            {
                args.IsValid = false;
            }
            else
                args.IsValid = true;
        }

        catch (Exception ex)
        {
            args.IsValid = false;
        }
    }

    protected void addNewRegFormSaveButton_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            //1. add new user       -> RegFormStep2Panel 
            //2. edit user          -> RegFormStep1Panel 
            //3. add new subuser    -> RegFormStep5Panel  
            //4. edit subuser       -> RegFormStep5Panel 
            //5. not saved          -> null
            int typeOperation = 1;
            string user_code = txtCode.Text;
            string captcha_code = Session["CAPTCHA_CODE"].ToString();

            if (user_code == captcha_code && RegFormChekEmailExistValidator.IsValid && accept_CheckBox.Checked)
            {
                errorLabelLabel.Visible = false;
                int parentID = 0;
                if (CheckServerObject())
                {
                    try
                    {
                        if (Session["UserData"] != null)
                        {
                            DataTable userData = (DataTable)Session["UserData"];
                            if (userData != null && userData.Rows.Count > 0)
                            {
                                parentID = (int)userData.Rows[0]["ID"];
                            }
                        }
                        bool isJuridic = false;
                        if (isPersonJuridiHiddenFieldID.Value.Equals("0"))
                        {
                            isJuridic = false;
                        }
                        else
                        {
                            isJuridic = true;
                        }
                        string nameString = nameTextBox.Text.Trim();
                        string prenumeString = isJuridic ? string.Empty : prenumeTextBox.Text.Trim();
                        string oldNameString = isJuridic ? string.Empty : oldNameTextBox.Text.Trim();
                        string pasaportString = pasaportTextBox.Text.Trim();
                        

                        DateTime dataNastre = DateTime.MinValue;
                        if (!isJuridic)
                        {
                            string[] dataNastere = dataNastereTextBox.Text.Split('.');

                            if (dataNastere.Length == 3)
                            {
                                int dey = 0;
                                int month = 0;
                                int year = 0;
                                int.TryParse(dataNastere[0], out dey);
                                int.TryParse(dataNastere[1], out month);
                                int.TryParse(dataNastere[2], out year);
                                if (dey != 0 && month != 0 && year != 0)
                                {
                                    dataNastre = new DateTime(year, month, dey);
                                }
                            }
                        }



                        string eliberatDe = eliberatDeTextBox.Text.Trim();

                        int countryGenezaID = 0;

                        string locNastereString = isJuridic ? string.Empty : localityGenezaTextBox.Text.Trim();

                        int sexID = 0;

                        string cetatenieString = isJuridic ? string.Empty : cetatenieTextBox.Text.Trim();
                        string nameTataString = nameTataTextBox.Text.Trim();
                        string nameMamaString = isJuridic ? string.Empty : nameMamaTextBox.Text.Trim();

                        string addresDomString = addresDomTextBox.Text.Trim();

                        int countryDomID = 0;
                       
                        int judetDomID = 0;

                        string telefonString = telefonTextBox.Text.Trim();
                        string emailString = string.Empty;
                        string passwordString = string.Empty;
                        if (emailDiv.Visible)
                        {
                            emailString = emailTextBox.Text.Trim();
                        }

                        if (fieldPassword.Visible)
                        {
                            passwordString = passwordTextBox.Text.Trim();
                        }

                        if (!isJuridic)
                        {
                            int.TryParse(countryNastereDDL.SelectedValue, out countryGenezaID);
                            int.TryParse(sexDDL.SelectedValue, out sexID); 
                            int.TryParse(countryDomDDL.SelectedValue, out countryDomID);
                            int.TryParse(judeteDDL.SelectedValue, out judetDomID);
                        }
                        
                        DateTime dataExpPasaportString = DateTime.MinValue;
                        if(!isJuridic)
                        {
                            string[] dataExpirPas = dataExpPasaportTextBox.Text.Split('.');

                            if (dataExpirPas.Length == 3)
                            {
                                int dey = 0;
                                int month = 0;
                                int year = 0;
                                int.TryParse(dataExpirPas[0], out dey);
                                int.TryParse(dataExpirPas[1], out month);
                                int.TryParse(dataExpirPas[2], out year);
                                if (dey != 0 && month != 0 && year != 0)
                                {
                                    dataExpPasaportString = new DateTime(year, month, dey);
                                }
                            }
                        }


                        string cnp = cnpTextBox.Text.Trim();

                        DateTime dataEliberarePasaport = DateTime.MinValue;
                        if (!isJuridic)
                        {                            
                            string[] dataEliberPas = personalDataEliberarePasaportTextBox.Text.Split('.');

                            if (dataEliberPas.Length == 3)
                            {
                                int dey = 0;
                                int month = 0;
                                int year = 0;
                                int.TryParse(dataEliberPas[0], out dey);
                                int.TryParse(dataEliberPas[1], out month);
                                int.TryParse(dataEliberPas[2], out year);
                                if (dey != 0 && month != 0 && year != 0)
                                {
                                    dataEliberarePasaport = new DateTime(year, month, dey);
                                }
                            }
                        }

                        int rudenieID = 0;
                        if (gradRudenieDropDownList.Items.Count > 0 && gradRudenieDropDownList.SelectedIndex != -1)
                        {
                            string stringRudenie = gradRudenieDropDownList.SelectedValue;
                            int.TryParse(stringRudenie, out rudenieID);
                        }

                        int duplicateID = mServerObject.GetSolicitantByKey(nameString, prenumeString, dataNastre, locNastereString);
                        if (duplicateID == 0)
                        {
                            #region add new user/subuser
                            if (mServerObject.AddNewSolicitant(parentID,
                                nameString, prenumeString, oldNameString,
                                pasaportString, dataNastre, countryGenezaID, locNastereString,
                                sexID, cetatenieString, nameTataString, nameMamaString,
                                addresDomString, countryDomID, judetDomID, telefonString, emailString, passwordString, dataExpPasaportString, rudenieID, cnp, dataEliberarePasaport, eliberatDe))
                            {


                                int returnUserID = mServerObject.GetSolicitantByKey(nameString, prenumeString, dataNastre, locNastereString);
                                if (returnUserID != 0)
                                {
                                    if (parentID == 0)
                                    {
                                        #region sendEmail
                                        DataTable userDataTable = mServerObject.GetSolicitantiByUserID(returnUserID);
                                        if (userDataTable != null && userDataTable.Rows.Count == 1)
                                        {
                                            string stringGUID = userDataTable.Rows[0]["refNumber"].ToString();
                                            string stringLink = string.Empty;
                                            if (!string.IsNullOrEmpty(stringGUID))
                                            {
                                                string applicationPath = Request.ApplicationPath;
                                                string serverIP = Request.ServerVariables["LOCAL_ADDR"].ToString();
                                                string serverPort = Request.ServerVariables["SERVER_PORT"].ToString();

                                                // ApplicationPath = /PROGRAMARE
                                                
                                                //stringLink = "http://178.168.4.51/programare/activate.aspx?refNumber=" + stringGUID;

                                                stringLink = "http://" + serverIP + (!serverPort.Equals(string.Empty) ? ":" + serverPort : string.Empty) + applicationPath + "/activate.aspx?refNumber=" + stringGUID;
                                            }
                                            mServerObject.InfoText(this, "Pentru " + nameString + " datele au fost salvate cu succes!");

                                            string emailTemplate = @"Buna ziua, <br/> "
                                                + "Ati solicitat crearea unui cont personal pe portalul pentru programarea serviciilor consulare <br />"
                                                + "al Ministerului Afacerilor Externe al României: eConsulat. <br/>"
                                                + "Pentru a confirma interesul dvs va rugam sa urmati link-ul de mai jos: <br/>"
                                                + " <a href='" + stringLink + "'> Apasati aici pentru activarea contului personal </a> <br /> "
                                                //+ "In cazul ca Link-ul nu lucreaza va rugam sa copiati textul urmator si sa il puneti manual in 'Address bar' al Browserului dm. "
                                                //+ stringLink + " <br/> "
                                                + "In cazul in care nu ati solicitat crearea unui cont personal pe site-ul eConsulat, <br />"
                                                + "va rugam sa nu luati in considerare acest email. <br>"
                                                + "Cu stima, <br/>"
                                                + "Ministerul Afacerilor Externe <br/>"
                                                + "ROMANIA"
                                                + " ";
                                            string emailSubject = "Mesaj de confirmare pentru  activarea contului personal pe eConsulat!";
                                            string resultEmail = Utils.EmailSend(emailString, emailTemplate, emailSubject);

                                        }
                                        #endregion send email
                                    }
                                    else
                                    {
                                        typeOperation = 3;
                                    }
                                }
                            }
                            else
                            {
                                mServerObject.InfoText(this, "Pentru " + nameString + " datele NU au fost SALVATE!. Verificati!");
                                typeOperation = 5;
                            }
                            #endregion
                        }
                       
                    }
                    catch (Exception ex)
                    {
                        mServerObject.InfoText(this, "Unable to save Solicitanti" + ex.Message);
                        typeOperation = 5;
                    }

                }
                else
                {
                    Response.Redirect("home.aspx", true);
                }
            }
            else
            {
                errorLabelLabel.Visible = true;
                typeOperation = 5;
            }
            switch (typeOperation)
            {
                case 1:
                    ShowPanel(RegFormStep2Panel.ID);
                    break;
                case 2:
                    ShowPanel(RegFormStep1Panel.ID);
                    break;
                case 3:
                    ShowPanel("RegFormStep5Panel");
                    break;
                case 4:
                    ShowPanel("RegFormStep5Panel");
                    break;
                default:
                    break;
            }
        }
    }
             
    private void ClearRegForm()
    {
        nameTextBox.Text = string.Empty;
        prenumeTextBox.Text = string.Empty;
        oldNameTextBox.Text = string.Empty;
        pasaportTextBox.Text = string.Empty;
        dataNastereTextBox.Text = string.Empty;
        countryNastereDDL.SelectedIndex = -1;
        localityGenezaTextBox.Text = string.Empty;
        sexDDL.SelectedIndex = -1;
        cetatenieTextBox.Text = string.Empty;
        nameTataTextBox.Text = string.Empty;
        nameMamaTextBox.Text = string.Empty;
        addresDomTextBox.Text = string.Empty;
        countryDomDDL.SelectedIndex = -1;
        judeteDDL.DataSource = null;
        judeteDDL.DataBind();
        telefonTextBox.Text = string.Empty;
        emailTextBox.Text = string.Empty;
        passwordTextBox.Text = string.Empty;
        dataExpPasaportTextBox.Text = string.Empty;
        gradRudenieDropDownList.SelectedIndex = -1;
        cnpTextBox.Text = string.Empty;
        dataEliberarePasaportTextBox.Text = string.Empty;
    }

    protected void RegForm1CancelButton_Click(object sender, EventArgs e)
    {
        //ShowPanel(stapeZeroPanel.ID);
        ClearRegForm();
        Response.Redirect("Default.aspx");
    }
    
    private void FillLocalitySelector(string parentString, DropDownList resultDropDownList)
    {
        int parentID = 0;
        int.TryParse(parentString, out parentID);
        DataTable typeClassifier = mServerObject.GetClassifiersByParentID(parentID);
        if (typeClassifier != null && typeClassifier.Rows.Count > 0)
        {
            mServerObject.fillFrontPageSelector(resultDropDownList, typeClassifier, "Name", "Code");
        }
    }

    protected void countryDomDDL_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillJudeteDLL();      
    }

    private void FillJudeteDLL()
    {
        int idTara = 0;
        int.TryParse(countryDomDDL.SelectedValue, out idTara);

        DataTable judeteList = mServerObject.GetJudeteList(idTara);
        mServerObject.fillFrontPageSelector(judeteDDL, judeteList, "DenumireJudet", "IdJudet");       
    }  
            
    #endregion RegForm1Panel

    #region RegForm3Panel

    protected void RegForm3Calendar_DayRender(object sender, DayRenderEventArgs e)
    {
        if (e.Day.Date <= DateTime.Now.Date )
        {
            e.Day.IsSelectable = false;
        } 
    }

    //private string ReturnDinamcTable(DataTable inputDT, int border)
    //{
    //    string result = string.Empty;
    //    string familyString = "*";

    //    for (int i = 0; i < programareFamilyMembersGridView.Rows.Count; i++)
    //    {
    //        CheckBox cb = (CheckBox)programareFamilyMembersGridView.Rows[i].FindControl("StatusCheked");

    //        if (cb != null && cb.Checked)
    //        {
    //            int fId = 0;
    //            int.TryParse(programareFamilyMembersGridView.Rows[i].Cells[1].Text, out fId);
    //            familyString += "@" + fId.ToString() + "_" + programareFamilyMembersGridView.Rows[i].Cells[2].Text + " " 
    //                                + programareFamilyMembersGridView.Rows[i].Cells[3].Text + " " 
    //                                + programareFamilyMembersGridView.Rows[i].Cells[4].Text;
    //        }
    //    }



    //    int idConsulat = 0;
    //    if (Session["UserData"] != null)
    //    {
    //        DataTable userData = (DataTable)Session["UserData"];
    //        if (userData != null && userData.Rows.Count == 1)
    //        {
    //            idConsulat = (int)userData.Rows[0]["PreferedIdConsulat"];
    //        }
    //    }

    //    string stringConsulat = idConsulat.ToString();
    //    string stringServiciu = ServiciuRegForm3Selector.SelectedValue;
    //    string stringData = string.Empty;
    //    string stringHour = string.Empty;

    //    if (inputDT != null && inputDT.Rows.Count > 0)
    //    {
    //        result += "<Table border='" + border + "'b>";

    //        result += "<tr>";
    //        for (int i = 0; i < inputDT.Columns.Count; i++)
    //        {
    //            result += "<td> " + inputDT.Columns[i].ColumnName + "</td>";
    //        }
    //        result += "</tr>";

    //        for (int i = 0; i < inputDT.Rows.Count; i++)
    //        {
    //            result += "<tr>";
    //            for (int j = 0; j < inputDT.Columns.Count; j++)
    //            {
    //                stringData = inputDT.Columns[j].ColumnName.ToString();
    //                stringHour = inputDT.Rows[i][j].ToString();
    //                string realLink = stringConsulat + "_" + stringServiciu + "_" + stringData + "_" + stringHour + familyString;
    //                string encodedlink = mServerObject.CreateEncodedString(realLink);
    //                encodedlink = Server.UrlEncode(encodedlink);

    //                result += "<td><a href=\"?programare=" + HttpUtility.UrlEncode(encodedlink) + "\">" + stringHour + "</a></td>";
    //            }
    //            result += "</tr>";
    //        }
    //        result += "</Table>";
    //    }

    //    return result;
    //}


    private string ReturnDinamcTable(DataTable inputDT, int border)
    {
        string result = string.Empty;
        string familyString = "*";

        for (int i = 0; i < programareFamilyMembersGridView.Rows.Count; i++)
        {
            CheckBox cb = (CheckBox)programareFamilyMembersGridView.Rows[i].FindControl("StatusCheked");

            if (cb != null && cb.Checked)
            {
                familyString += "@" + programareFamilyMembersGridView.Rows[i].Cells[1].Text
                                    + "_" + programareFamilyMembersGridView.Rows[i].Cells[5].Text
                                    + "_" + programareFamilyMembersGridView.Rows[i].Cells[2].Text
                                    + " " + programareFamilyMembersGridView.Rows[i].Cells[3].Text
                                    + " " + programareFamilyMembersGridView.Rows[i].Cells[4].Text;
            }
        }



        int idConsulat = 0;
        if (Session["UserData"] != null)
        {
            DataTable userData = (DataTable)Session["UserData"];
            if (userData != null && userData.Rows.Count == 1)
            {
                idConsulat = (int)userData.Rows[0]["PreferedIdConsulat"];
            }
        }

        string stringConsulat = idConsulat.ToString();
        string stringServiciu = ServiciuRegForm3Selector.SelectedValue;
        string stringData = string.Empty;
        string stringHour = string.Empty;
        string idCalendar = string.Empty;

        if (inputDT != null && inputDT.Rows.Count > 0)
        {
            result += "<Table cellpadding=\"5\" border=\"" + border + "\">";

            for (int i = 0; i < inputDT.Rows.Count; )
            {
                result += "<tr>";

                for (int j = 0; j < 4 && j < inputDT.Rows.Count; j++)
                {
                    result += "<td>";
                    if (i < inputDT.Rows.Count)
                    {
                        stringData = inputDT.Columns[0].ColumnName.ToString();
                        stringHour = inputDT.Rows[i][0].ToString();
                        idCalendar = inputDT.Rows[i][1].ToString();

                        string realLink = stringConsulat + "_" + stringServiciu + "_" + stringData + "_" + stringHour + "_" + idCalendar + familyString;
                        string encodedlink = mServerObject.CreateEncodedString(realLink);
                        encodedlink = Server.UrlEncode(encodedlink);

                        result += "<a href=\"?programare=" + HttpUtility.UrlEncode(encodedlink) + "\">" + stringHour + "</a>";
                    }
                    result += "</td>";
                    i++;
                }

                result += "</tr>";
            }
            result += "</Table>";
        }
        else
        {
            result += "<p> NU SUNT ORE DISPONIBILE PENTRU PROGRAMARE</p>";
        }

        return result;
    }  

    protected void RegForm3Calendar_SelectionChanged(object sender, EventArgs e)
    {
        int idService = 0;
        int.TryParse(ServiciuRegForm3Selector.SelectedValue, out idService);
        
        int idConsulat = 0;
        if (Session["UserData"] != null)
        {
            DataTable userData = (DataTable)Session["UserData"];
            if (userData != null && userData.Rows.Count == 1)
            {
                idConsulat = (int)userData.Rows[0]["PreferedIdConsulat"];
            }
        }

        DateTime dateFrom = RegForm3Calendar.SelectedDate;
        int minRent = 0;

        for (int i = 0; i < programareFamilyMembersGridView.Rows.Count; i++)
        {
            CheckBox cb = (CheckBox)programareFamilyMembersGridView.Rows[i].FindControl("StatusCheked");

            if (cb != null && cb.Checked)
            {
                minRent++;
            }
        }
        
        DataTable hoursAviable = mServerObject.GetAviableServiceInterval(idConsulat, idService, dateFrom, minRent);

        detailsDataGrid = ReturnDinamcTable(hoursAviable, 1);
        
        //programareGridView.DataSource = hoursAviable;
        //CreateGridView(programareGridView, hoursAviable);       
        //programareGridView.DataBind();
    }
       

    #endregion RegForm3Panel

    #region menuRegForm

    protected void programareRegForm_Click(object sender, EventArgs e)
    {
        ShowPanel(RegFormStep3PanelFamilySelection.ID);
        mServerObject.InfoText(this, string.Empty);
    }
    
    protected void personalRegForm_Click(object sender, EventArgs e)
    {
        ShowPanel(personalInfoTablePanel.ID);
        mServerObject.InfoText(this, string.Empty);
    }
    
    protected void familyRegForm_Click(object sender, EventArgs e)
    {
        ShowPanel(RegFormFamiliaPanel.ID);
        mServerObject.InfoText(this, string.Empty);
    }

    protected void statisticaInregistrarilorRegForm_Click(object sender, EventArgs e)
    {
            ShowPanel(statisticaInregistrarilorPanel.ID);
    }

    protected void settingsRegForm_Click(object sender, EventArgs e)
    {
        ShowPanel(RegFormStep6Panel.ID);
        mServerObject.InfoText(this, string.Empty);
    }

    #endregion menuRegForm
       

    protected void showNextStep1Button_Click(object sender, EventArgs e)
    {
        //ShowPanel(RegFormStep1Panel.ID);
        ShowPanel(RegFormSelectPersonTypePanel.ID);
    }   

    #region RegForm6
    protected void updateRegForm6SaveButton_Click(object sender, EventArgs e)
    {
        if (CheckServerObject())
        {
            try
            {
                int editUserID = 0;
                string passwordString = string.Empty;
                if (Session["UserData"] != null)
                {
                    DataTable userData = (DataTable)Session["UserData"];

                    editUserID = (int)userData.Rows[0]["ID"];
                    DataTable getData = mServerObject.GetSolicitantiByUserID(editUserID);
                    if (getData != null && getData.Rows.Count > 0)
                    {
                        passwordString = getData.Rows[0]["Parola"].ToString();
                    }

                    if (mServerObject.UpdatePasswordRegForm(editUserID, passwordString))
                    {
                        ShowPanel(RegFormStep3Panel.ID);
                        mServerObject.InfoText(this, "Noua parola a fost salvata!");
                        ClearRegForm6();
                    }
                    else
                    {
                        mServerObject.InfoText(this, "Datele NU au fost SALVATE! Verificati!");
                    }
                }
            }
            catch (Exception ex)
            {
                mServerObject.InfoText(this, "Unable to save Solicitanti" + ex.Message);
            }
        }
        else
        {
            ShowPanel(stapeZeroPanel.ID);
        }

    }

    private void ClearRegForm6()
    {
        oldPasswordRegForm6TextBox.Text = string.Empty;
        newPasswordRegForm6TextBox.Text = string.Empty;
    }
    
    protected void cancelRegForm6Button_Click(object sender, EventArgs e)
    {
        ShowPanel(RegFormStep3Panel.ID);
        ClearRegForm6();
    }
    
    #endregion RegForm6

    protected void CreateGridView(GridView sourceGridView, DataTable sourceDataTable)
    {
        //BuildButtonField(sourceDataTable);
        
        sourceGridView.Columns.Clear();

        sourceGridView.AutoGenerateColumns = true;
        
        sourceGridView.DataSource = sourceDataTable;

        #region ButtonField

        

        #endregion ButtonField
    }
 

    #region BuildFields

    ButtonField GetButtonField(string commandName, string textButton)
    {
        ButtonField submitButton = new ButtonField();
        submitButton.ButtonType = ButtonType.Button;
        //submitButton.CommandName = commandName;
        submitButton.Text = textButton;
        submitButton.HeaderText = textButton;
        return submitButton;
    }
        
        
    private int GetColumnIndexByName(GridView grid, string name)
    {
        foreach (DataControlField col in grid.Columns)
        {
            if (col.HeaderText.ToLower().Trim() == name.ToLower().Trim())
            {
                return grid.Columns.IndexOf(col);
            }
        }
        return -1;
    }

    #endregion BuildFields

    private void FillFamilyMemdersForm()
    {
        ClearFamiliaDataPanel();
        string membruFamString = membruFamilieDropDownList.SelectedValue;
        int memruFamiliei = 0;
        int.TryParse(membruFamString, out memruFamiliei);
        if (memruFamiliei != 0)
        {
            DataTable formData = mServerObject.GetSolicitantiByUserID(memruFamiliei);
            if (formData != null && formData.Rows.Count > 0)
            {
                familiaNameTextBox.Text = formData.Rows[0]["Nume"].ToString();
                familiaPrenumeTextBox.Text = formData.Rows[0]["Prenume"].ToString();
                familiaOldNameTextBox.Text = formData.Rows[0]["NumeAnterior"].ToString();
                familiaPasaportTextBox.Text = formData.Rows[0]["Pasaport"].ToString();
                familiaCnpTextBox.Text = formData.Rows[0]["cnp"].ToString();

                string stringData = formData.Rows[0]["DataNastere"].ToString();
                DateTime datanastere = DateTime.MinValue;
                DateTime emptyDate = DateTime.MinValue;
                DateTime.TryParse(stringData, out datanastere);

                if (datanastere != emptyDate)
                    familiaDataNastereTextBox.Text = datanastere.ToShortDateString();
                else
                    familiaDataNastereTextBox.Text = string.Empty;

                try
                {
                    familiaCountryNastereDDL.SelectedValue = formData.Rows[0]["TaraNastereID"].ToString();
                }
                catch { }

                familiaLocalityGenezaTextBox.Text = formData.Rows[0]["LocNastere"].ToString();

                try
                {
                    familiaSexDDL.SelectedValue = formData.Rows[0]["SexID"].ToString();
                }
                catch { }

                try
                {
                    gradRudenieDropDownList.SelectedValue = formData.Rows[0]["RudenieID"].ToString();
                }
                catch { }

                familiaCetatenieTextBox.Text = formData.Rows[0]["Cetatenie"].ToString();
                familiaNameTataTextBox.Text = formData.Rows[0]["NumeTata"].ToString();
                perosnalNameMamaTextBox.Text = formData.Rows[0]["NumeMama"].ToString();
                familiaAddresDomTextBox.Text = formData.Rows[0]["Domiciliu"].ToString();
                try
                {
                    familiaCountryDomDDL.SelectedValue = formData.Rows[0]["TaraDomiciliuID"].ToString();
                }
                catch { }

                try
                {
                    FillfamiliaJudeteDLL();
                    familiaJudeteDDL.SelectedValue = formData.Rows[0]["JudetDomiciliuID"].ToString();
                }
                catch
                {
                    FillfamiliaJudeteDLL();
                }

                familiaTelefonTextBox.Text = formData.Rows[0]["Telefon"].ToString();
                familiaEliberatDeTextBox.Text = formData.Rows[0]["EmitentPasaport"].ToString();

                string stringDataExpPas = formData.Rows[0]["DataExpPasaport"].ToString();
                DateTime datExpPas = DateTime.MinValue;
                DateTime.TryParse(stringDataExpPas, out datExpPas);

                if (datExpPas != emptyDate)
                    familiaDataExpPasaportTextBox.Text = datExpPas.ToShortDateString();
                else
                    familiaDataExpPasaportTextBox.Text = string.Empty;

                string stringDataEliberariiPas = formData.Rows[0]["DataEmiterePasaport"].ToString();
                DateTime dataEmitereP = DateTime.MinValue;
                DateTime.TryParse(stringDataEliberariiPas, out dataEmitereP);

                if (dataEmitereP != emptyDate)
                    familiaDataEliberarePasaportTextBox.Text = dataEmitereP.ToShortDateString();
                else
                    familiaDataEliberarePasaportTextBox.Text = string.Empty;
            }
        }       
    }

    protected void membruFamilieDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        string selectedValue = membruFamilieDropDownList.SelectedValue;
        if (selectedValue.Equals("0"))
        {
            ClearFamiliaDataPanel();
            newFamilyMemberHiddenField.Value = "New";
        }
        else
        {
            FillFamilyMemdersForm();
            newFamilyMemberHiddenField.Value = "Old";
        }
    }

    protected void FamilySelectionOkButton_Click(object sender, EventArgs e)
    {
        ShowPanel(RegFormStep3Panel.ID);
    }

    protected void statisticaInregistrarilorGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int rowIndex = e.RowIndex;
        if (CheckServerObject())
        {
            int idProgramare = 0;
            int.TryParse(statisticaInregistrarilorGridView.Rows[rowIndex].Cells[0].Text, out idProgramare);

            if (mServerObject.AnulareProgramare(idProgramare))
            {
                mServerObject.InfoText(this, "Datele au fost STERSE!");
                ShowPanel(statisticaInregistrarilorPanel.ID);
            }
        }
    }

    protected void deleteButton_DataBinding(object sender, System.EventArgs e)
    {
        Button btn = (Button)(sender);
        bool expiratOrNU = (bool)(Eval("ButtonState"));

        btn.Visible = expiratOrNU;
        btn.Enabled = expiratOrNU;
    }

    protected void personFizicButton_Click(object sender, EventArgs e)
    {
        isPersonJuridiHiddenFieldID.Value = "0";
        ShowPanel(RegFormStep1Panel.ID);
    }

    protected void personJuridicButton_Click(object sender, EventArgs e)
    {
        isPersonJuridiHiddenFieldID.Value = "1";
        ShowPanel(RegFormStep1Panel.ID);
    }      
    
    #region Pesonal Data

    private void FillPersonalDataPanel()
    {
        int userID = mServerObject.UserID;

        DataTable formData = mServerObject.GetSolicitantiByUserID(userID);
        if (formData != null && formData.Rows.Count > 0)
        {
            personalNameTextBox.Text = formData.Rows[0]["Nume"].ToString();
            personalPrenumeTextBox.Text = formData.Rows[0]["Prenume"].ToString();
            personalOldNameTextBox.Text = formData.Rows[0]["NumeAnterior"].ToString();
            personalPasaportTextBox.Text = formData.Rows[0]["Pasaport"].ToString();
            personalCnpTextBox.Text = formData.Rows[0]["cnp"].ToString();

            string stringData = formData.Rows[0]["DataNastere"].ToString();
            DateTime datanastere = DateTime.MinValue;
            DateTime emptyDate = DateTime.MinValue;
            DateTime.TryParse(stringData, out datanastere);

            if (datanastere != emptyDate)
                personalDataNastereTextBox.Text = datanastere.ToShortDateString();
            else
                personalDataNastereTextBox.Text = string.Empty;

            try
            {
                personalCountryNastereDDL.SelectedValue = formData.Rows[0]["TaraNastereID"].ToString();
            }
            catch  {  }

            personalLocalityGenezaTextBox.Text = formData.Rows[0]["LocNastere"].ToString();

            try
            {
                personalSexDDL.SelectedValue = formData.Rows[0]["SexID"].ToString();
            }
            catch  {  }

            personalCetatenieTextBox.Text = formData.Rows[0]["Cetatenie"].ToString();
            personalNameTataTextBox.Text = formData.Rows[0]["NumeTata"].ToString();
            perosnalNameMamaTextBox.Text = formData.Rows[0]["NumeMama"].ToString();
            personalAddresDomTextBox.Text = formData.Rows[0]["Domiciliu"].ToString();
            try
            {
                personalCountryDomDDL.SelectedValue = formData.Rows[0]["TaraDomiciliuID"].ToString();
            }
            catch  { }

            try
            {
                FillPersonalJudeteDLL();
                personalJudeteDDL.SelectedValue = formData.Rows[0]["JudetDomiciliuID"].ToString();
            }
            catch
            {
                FillPersonalJudeteDLL();
            }

            personalTelefonTextBox.Text = formData.Rows[0]["Telefon"].ToString(); 
            personalEmailTextBox.Text = formData.Rows[0]["Email"].ToString();
            personalEliberatDeTextBox.Text = formData.Rows[0]["EmitentPasaport"].ToString();  

            string stringDataExpPas = formData.Rows[0]["DataExpPasaport"].ToString();
            DateTime datExpPas = DateTime.MinValue;
            DateTime.TryParse(stringDataExpPas, out datExpPas);

            if (datExpPas != emptyDate)
                personalDataExpPasaportTextBox.Text = datExpPas.ToShortDateString();
            else
                personalDataExpPasaportTextBox.Text = string.Empty;

            string stringDataEliberariiPas = formData.Rows[0]["DataEmiterePasaport"].ToString();
            DateTime dataEmitereP = DateTime.MinValue;
            DateTime.TryParse(stringDataEliberariiPas, out dataEmitereP);

            if (dataEmitereP != emptyDate)
                personalDataEliberarePasaportTextBox.Text = dataEmitereP.ToShortDateString();
            else
                personalDataEliberarePasaportTextBox.Text = string.Empty;           
        }
    }

    private void ClearPersonalDataPanel()
    {
        personalNameTextBox.Text = string.Empty;
        personalPrenumeTextBox.Text = string.Empty;
        personalOldNameTextBox.Text = string.Empty;
        personalDataNastereTextBox.Text = string.Empty;
        personalCountryNastereDDL.SelectedIndex = -1;
        personalLocalityGenezaTextBox.Text = string.Empty;

        personalCetatenieTextBox.Text = string.Empty;
        personalCnpTextBox.Text = string.Empty;
        personalNameTataTextBox.Text = string.Empty;
        perosnalNameMamaTextBox.Text = string.Empty;
        personalAddresDomTextBox.Text = string.Empty;
        personalSexDDL.SelectedIndex = -1;
        personalCountryDomDDL.SelectedIndex = -1;
        personalJudeteDDL.SelectedIndex = -1;
        personalTelefonTextBox.Text = string.Empty;
        personalEmailTextBox.Text = string.Empty;
        personalPasaportTextBox.Text = string.Empty;
        personalEliberatDeTextBox.Text = string.Empty;
        personalDataEliberarePasaportTextBox.Text = string.Empty;
        personalDataExpPasaportTextBox.Text = string.Empty;
    }

    protected void FillPersonalJudeteDLL()
    {
        int idTara = 0;
        int.TryParse(personalCountryDomDDL.SelectedValue, out idTara);

        DataTable judeteList = mServerObject.GetJudeteList(idTara);
        mServerObject.fillFrontPageSelector(personalJudeteDDL, judeteList, "DenumireJudet", "IdJudet");   
    }

    protected void personalCountryDomDDL_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillPersonalJudeteDLL();
    }

    protected void personalDataCancelButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("home.aspx", true);
    }

    protected void personalDataSaveButton_Click(object sender, EventArgs e)
    {
        int userID = mServerObject.UserID;
        int rudenieID = 0;
        int parentID = 0;

        string name = personalNameTextBox.Text.Trim();
        string prenume = personalPrenumeTextBox.Text.Trim();
        string numelaNastere = personalOldNameTextBox.Text.Trim();
        string cnp = personalCnpTextBox.Text.Trim();

        DateTime dataNastere = DateTime.MinValue;
        DateTime.TryParse(personalDataNastereTextBox.Text, out dataNastere);
        
        string pasaport = personalPasaportTextBox.Text.Trim();

        int countryNastere = 0;
        int.TryParse(personalCountryNastereDDL.SelectedValue, out countryNastere);

        string locNastere = personalLocalityGenezaTextBox.Text.Trim();

        int sexID = 0;
        int.TryParse(personalSexDDL.SelectedValue, out sexID);
        string cetataniaStr = personalCetatenieTextBox.Text.Trim();
        string tata = personalNameTataTextBox.Text.Trim();
        string mama = perosnalNameMamaTextBox.Text.Trim();
        string domiciliu = personalAddresDomTextBox.Text.Trim();

        int countryDom = 0;
        int.TryParse(personalCountryDomDDL.SelectedValue, out countryDom);

        int judetDom = 0;
        int.TryParse(personalJudeteDDL.SelectedValue, out judetDom);

        string telefon = personalTelefonTextBox.Text.Trim();
        string email = personalEmailTextBox.Text.Trim();    
        
        DateTime dataEliberarePasaport = DateTime.MinValue;
        DateTime.TryParse(personalDataEliberarePasaportTextBox.Text, out dataEliberarePasaport);        

        DateTime dataExpirarePasaport = DateTime.MinValue;
        DateTime.TryParse(personalDataExpPasaportTextBox.Text, out dataExpirarePasaport);        

        string eliberatDe = personalEliberatDeTextBox.Text.Trim();

        if (mServerObject.UpdateSolicitantiPersonalData(userID,
                                                        parentID,
                                                        name, 
                                                        prenume, 
                                                        numelaNastere, 
                                                        pasaport, 
                                                        dataNastere, 
                                                        countryNastere, 
                                                        locNastere,
                                                        cnp,
                                                        sexID, 
                                                        cetataniaStr, 
                                                        tata, 
                                                        mama, 
                                                        domiciliu, 
                                                        countryDom, 
                                                        judetDom, 
                                                        telefon,
                                                        email,
                                                        dataExpirarePasaport,
                                                        rudenieID,
                                                        dataEliberarePasaport,
                                                        eliberatDe))
        {
            mServerObject.InfoText(this, "Pentru " + name + " " + prenume + " datele au fost SALVATE!");
        }
    }
    
    #endregion Personal Data


    #region Familia

    private void ClearFamiliaDataPanel()
    {
        familiaNameTextBox.Text = string.Empty;
        familiaPrenumeTextBox.Text = string.Empty;
        familiaOldNameTextBox.Text = string.Empty;
        familiaDataNastereTextBox.Text = string.Empty;
        familiaCountryNastereDDL.SelectedIndex = -1;
        familiaLocalityGenezaTextBox.Text = string.Empty;

        familiaCetatenieTextBox.Text = string.Empty;
        familiaCnpTextBox.Text = string.Empty;
        familiaNameTataTextBox.Text = string.Empty;
        familiaNameMamaTextBox.Text = string.Empty;
        familiaAddresDomTextBox.Text = string.Empty;
        familiaSexDDL.SelectedIndex = -1;
        familiaCountryDomDDL.SelectedIndex = -1;
        FillfamiliaJudeteDLL();
        familiaTelefonTextBox.Text = string.Empty;
        familiaPasaportTextBox.Text = string.Empty;
        familiaEliberatDeTextBox.Text = string.Empty;
        familiaDataEliberarePasaportTextBox.Text = string.Empty;
        familiaDataExpPasaportTextBox.Text = string.Empty;
    }
      
    protected void familiaDataSaveButton_Click(object sender, EventArgs e)
    {
        int parentID = mServerObject.UserID;

        string name = familiaNameTextBox.Text.Trim();
        string prenume = familiaPrenumeTextBox.Text.Trim();
        string numelaNastere = familiaOldNameTextBox.Text.Trim();

        DateTime dataNastere = DateTime.MinValue;
        DateTime.TryParse(familiaDataNastereTextBox.Text, out dataNastere);

        string pasaport = familiaPasaportTextBox.Text.Trim();

        int countryNastere = 0;
        int.TryParse(familiaCountryNastereDDL.SelectedValue, out countryNastere);

        string locNastere = familiaLocalityGenezaTextBox.Text.Trim();

        int sexID = 0;
        int.TryParse(familiaSexDDL.SelectedValue, out sexID);
        string cetataniaStr = familiaCetatenieTextBox.Text.Trim();
        string tata = familiaNameTataTextBox.Text.Trim();
        string mama = perosnalNameMamaTextBox.Text.Trim();
        string domiciliu = familiaAddresDomTextBox.Text.Trim();
        string cnp = familiaCnpTextBox.Text.Trim();

        int countryDom = 0;
        int.TryParse(familiaCountryDomDDL.SelectedValue, out countryDom);

        int judetDom = 0;
        int.TryParse(familiaJudeteDDL.SelectedValue, out judetDom);

        string telefon = familiaTelefonTextBox.Text.Trim();
        string email = string.Empty;

        DateTime dataEliberarePasaport = DateTime.MinValue;
        DateTime.TryParse(familiaDataEliberarePasaportTextBox.Text, out dataEliberarePasaport);

        DateTime dataExpirarePasaport = DateTime.MinValue;
        DateTime.TryParse(familiaDataExpPasaportTextBox.Text, out dataExpirarePasaport);

        string eliberatDe = familiaEliberatDeTextBox.Text.Trim();
        int rudenieID = 0;
        int.TryParse(gradRudenieDropDownList.SelectedValue, out rudenieID);

        bool resultOperation = false;
        int returnUserID = mServerObject.GetSolicitantByKey(name, prenume, dataNastere, locNastere);

        if (newFamilyMemberHiddenField.Value.Equals("New") && returnUserID == 0)
        {
            resultOperation = mServerObject.AddNewSolicitant(parentID, name, prenume, numelaNastere, pasaport, dataNastere, countryNastere, locNastere, sexID, cetataniaStr, tata, mama, domiciliu, countryDom, judetDom, telefon, email, string.Empty, dataExpirarePasaport, rudenieID, cnp, dataEliberarePasaport, eliberatDe);
        }
        else
        {            
            resultOperation = mServerObject.UpdateSolicitantiPersonalData(returnUserID, parentID, name, prenume, numelaNastere, pasaport, dataNastere, countryNastere, locNastere, cnp, sexID, cetataniaStr, tata, mama, domiciliu, countryDom, judetDom, telefon, email, dataExpirarePasaport, rudenieID, dataEliberarePasaport, eliberatDe);
        }

        if (resultOperation)
        {
            mServerObject.InfoText(this, "Pentru " + name + " " + prenume +" datele au fost SALVATE!");

            int parentUserID = mServerObject.UserID;

            DataTable familyList = mServerObject.GetFamilyListByUserID(parentUserID, false);
            if (familyList.Rows.Count == 0)
            { newFamilyMemberHiddenField.Value = "New"; }
            else
            { newFamilyMemberHiddenField.Value = "Old"; }

            familyList.Rows.Add();
            familyList.Rows[familyList.Rows.Count - 1]["Name"] = "--> Introduce Un Membru Nou <--";
            familyList.Rows[familyList.Rows.Count - 1]["Code"] = 0;
            mServerObject.fillFrontPageSelector(membruFamilieDropDownList, familyList, "Name", "Code");
            FillFamilyMemdersForm();
        }
        else { mServerObject.InfoText(this, "Pentru " + name + " " + prenume +" datele NU au fost SALVATE!"); }

    }

    protected void familiaDataCancelButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("home.aspx", true);
    }
    
    protected void familiaCountryDomDDL_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillfamiliaJudeteDLL();
    }

    private void FillfamiliaJudeteDLL()
    {
        int idTara = 0;
        int.TryParse(familiaCountryDomDDL.SelectedValue, out idTara);

        DataTable judeteList = mServerObject.GetJudeteList(idTara);
        mServerObject.fillFrontPageSelector(familiaJudeteDDL, judeteList, "DenumireJudet", "IdJudet"); 
    }

    #endregion Familia

    protected void AnulareRegForm6Button_Click(object sender, EventArgs e)
    {
        if (CheckServerObject())
        {
            if (mServerObject.AnulareCont(mServerObject.UserID))
            {
                Session["UserData"] = null;
                Session["ServerModule"] = null;
                Response.Redirect("Default.aspx", true);
            }
            else
            {
                mServerObject.InfoText(this, "Atentie! Contul nu a fost anulat! Incercati mai tirziu!");
            }
        }
    }
}
